﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using LinqToExcel;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using NSDrivingTest;

public partial class frmMain : Form
{

    const string ImagePath = @"D:\Egg Stuff\程式\C_Sharp\獨立方案\機車駕照筆試題庫程式\圖檔\";

    public frmMain()
    {
        InitializeComponent();
    }

    private void GenTestSheets( List<DrivingTestQuestion> dTQs, bool showAnswerInSheet, int numSheetToGen, int numQuestionsPerType, int numStartingSheet )
    {
        // creation of the document with a certain size and certain margins
        Document document = new Document(PageSize.A4, 65, 50, 20, 20);
        iTextSharp.text.Image image;
        int qN = 0;
        QuestionType[] qTypes = { QuestionType.法規是非題, QuestionType.法規選擇題, QuestionType.標誌_標線_號誌是非題, QuestionType.標誌_標線_號誌選擇題 };

        List<DrivingTestSheetAnswer> sheetAnswers = new List<DrivingTestSheetAnswer>();

        DrivingTestSheetAnswer sAns = null;

        try
        {

            // creation of the different writers
            PdfWriter writer = PdfWriter.GetInstance( document, new FileStream( string.Format( @"D:\Desktop\機車駕照筆試題庫{0}-{1}.pdf", numStartingSheet, numSheetToGen + numStartingSheet ), FileMode.Create ) );

            // step 4: we add content to the document
            FontFactory.Register( Environment.GetFolderPath( Environment.SpecialFolder.System ) + @"\..\Fonts\KAIU.TTF" );

            // 2010_05_19 全部變粗體
            iTextSharp.text.Font Kaiu12 = FontFactory.GetFont( "標楷體", BaseFont.IDENTITY_H, 12f );
            iTextSharp.text.Font Kaiu12B = FontFactory.GetFont( "標楷體", BaseFont.IDENTITY_H, 12f );
            Kaiu12B.SetStyle( iTextSharp.text.Font.BOLD );
            iTextSharp.text.Font Kaiu14 = FontFactory.GetFont( "標楷體", BaseFont.IDENTITY_H, 14f );
            iTextSharp.text.Font Kaiu14B = FontFactory.GetFont( "標楷體", BaseFont.IDENTITY_H, 14f );
            Kaiu14B.SetStyle( iTextSharp.text.Font.BOLD );

            iTextSharp.text.Font TimeNews18 = FontFactory.GetFont( FontFactory.TIMES_ROMAN, 18, iTextSharp.text.Font.BOLD );
            iTextSharp.text.Font TimeNews20 = FontFactory.GetFont( FontFactory.TIMES_ROMAN, 20, iTextSharp.text.Font.BOLD );

            BaseFont bf = BaseFont.CreateFont( Environment.GetFolderPath( Environment.SpecialFolder.System ) + @"\..\Fonts\KAIU.TTF",
                                                BaseFont.IDENTITY_H, BaseFont.EMBEDDED );

            document.Open();
            PdfPTable tableOfContent;

            for( int sheetNum = numStartingSheet; sheetNum <= numSheetToGen + numStartingSheet; ++sheetNum )
            {
                tableOfContent = new PdfPTable( 4 );
                tableOfContent.DefaultCell.PaddingBottom = 6f;
                tableOfContent.DefaultCell.PaddingTop = -1f;
                tableOfContent.DefaultCell.PaddingRight = 3;
                tableOfContent.DefaultCell.PaddingLeft = 3; //5
                tableOfContent.DefaultCell.BorderWidth = 0.5f;
                tableOfContent.DefaultCell.UseBorderPadding = false;
                tableOfContent.DefaultCell.UseVariableBorders = false;
                tableOfContent.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;// Element.ALIGN_MIDDLE;

                float[] headerwidths = { 7, 5, 11, 90 };   // 前面的號碼會跑掉:    { 8, 87, 15 }; 
                // 最一開始:            { 12, 83, 15 }  113
                tableOfContent.SetWidths( headerwidths );
                tableOfContent.WidthPercentage = 110; // 110

                tableOfContent.DefaultCell.Colspan = 4;
                tableOfContent.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                tableOfContent.AddCell( new Phrase( string.Format( "第{0}份", sheetNum ), Kaiu12B ) );
                tableOfContent.HeaderRows = 1;

                qN = 0;

                sAns = new DrivingTestSheetAnswer( sheetNum );

                foreach( QuestionType qt in qTypes )
                {
                    tableOfContent.DefaultCell.Colspan = 1;
                    tableOfContent.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    tableOfContent.AddCell( new Phrase( "答案", Kaiu12B ) );

                    tableOfContent.DefaultCell.Colspan = 3;
                    tableOfContent.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                    tableOfContent.AddCell( new Phrase( qt.ToString(), Kaiu12B ) );


                    foreach( DrivingTestQuestion d in dTQs.Where( dT => dT.Type == ( ( int ) qt ).ToString() ).OrderBy( p => Guid.NewGuid() ).Take( numQuestionsPerType ) )
                    {
                        tableOfContent.DefaultCell.Colspan = 1;
                        tableOfContent.DefaultCell.PaddingTop = -2f;
                        tableOfContent.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                        tableOfContent.AddCell( new Phrase( showAnswerInSheet ? d.Answer : string.Empty, Kaiu12 ) );
                        tableOfContent.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                        tableOfContent.AddCell( new Phrase( string.Format( "{0:00}", ++qN ), Kaiu12 ) );

                        sAns.QNAs.Add( new QuestionNumberAndAnswer( qN, d.Answer ) );

                        if( qt == QuestionType.標誌_標線_號誌是非題 || qt == QuestionType.標誌_標線_號誌選擇題 )
                        {
                            image = iTextSharp.text.Image.GetInstance( ImagePath + d.QuestionPicture );
                            image.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
                            //image.ScaleToFit( 50, 50 );
                            tableOfContent.DefaultCell.PaddingTop = 1f;
                            tableOfContent.AddCell( image );
                        }
                        else
                        {
                            tableOfContent.DefaultCell.Colspan = 2;
                        }
                        tableOfContent.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                        tableOfContent.DefaultCell.PaddingTop = 0f;
                        tableOfContent.AddCell( new Phrase( d.Question, Kaiu12 ) );
                    }

                }

                document.Add( tableOfContent );

                sheetAnswers.Add( sAns );

                document.NewPage();
            }

            if( true || !showAnswerInSheet )
            {
                int NumQuestionsInTR = 5;

                tableOfContent = new PdfPTable( NumQuestionsInTR * 2 );
                tableOfContent.DefaultCell.PaddingBottom = 6f;
                tableOfContent.DefaultCell.PaddingTop = -1f;
                tableOfContent.DefaultCell.PaddingRight = 3;
                tableOfContent.DefaultCell.PaddingLeft = 3; //5
                tableOfContent.DefaultCell.BorderWidth = 0.5f;
                tableOfContent.DefaultCell.UseBorderPadding = false;
                tableOfContent.DefaultCell.UseVariableBorders = false;
                tableOfContent.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;

                //float[] headerwidths = { 7, 5, 11, 90 };   // 前面的號碼會跑掉:    { 8, 87, 15 }; 
                // 最一開始:            { 12, 83, 15 }  113
                //tableOfContent.SetWidths( headerwidths );
                tableOfContent.WidthPercentage = 110; // 110


                foreach( DrivingTestSheetAnswer sA in sheetAnswers )
                {
                    tableOfContent.DefaultCell.Colspan = NumQuestionsInTR * 2;
                    tableOfContent.DefaultCell.HorizontalAlignment = Element.ALIGN_MIDDLE;
                    tableOfContent.AddCell( new Phrase( string.Format( "第{0}份試題答案", sA.SheetNumber ), Kaiu12B ) );

                    //tableOfContent.HeaderRows = 1;
                    foreach( QuestionNumberAndAnswer qA in sA.QNAs )
                    {
                        tableOfContent.DefaultCell.Colspan = 1;
                        tableOfContent.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                        tableOfContent.AddCell( new Phrase( string.Format("{0:00}", qA.Num), Kaiu12B ) );
                        tableOfContent.AddCell( new Phrase( qA.Ans, Kaiu12B ) );
                    }
                }
                document.Add( tableOfContent );
                document.NewPage();

            }

            document.Close();
        
        }
        catch( Exception ex )
        {
            MessageBox.Show( ex.ToString() );
        }

    }

    private void frmMain_Load( object sender, EventArgs e )
    {
        const string EXCEL_FILE = "Data.xlsx";
        const string SHEET_NAME = "題庫資料";
        const bool SHOW_ANSWER = false;
        const int NUM_SHEET_TO_GEN = 30;
        const int NUM_QUESTION_PER_TYPE = 10;       
        const int NUM_STARTING_SHEET = 21;

        var excel = new ExcelQueryFactory( EXCEL_FILE );
        var dTQs = from item in excel.Worksheet<DrivingTestQuestion>( SHEET_NAME ) select item;

        StringBuilder sb = new StringBuilder();

        try
        {

            //MessageBox.Show( string.Format( "總共有「{0}」題。", dTQs.Count() ) );

            GenTestSheets( dTQs.ToList(), SHOW_ANSWER, NUM_SHEET_TO_GEN, NUM_QUESTION_PER_TYPE, NUM_STARTING_SHEET );

            MessageBox.Show("OK!!!");
            this.Close();
            //foreach( DrivingTestQuestion d in dTQs )
            //{
            //    sb.AppendLine( d.ToString() );
            //}

            //MessageBox.Show( sb.ToString() );
        }
        catch( Exception ex )
        {
            MessageBox.Show( ex.ToString() );
        }

    }
}
